/**
 * 自定义菜单相关
 * @authors 杨兴洲（of2502）
 * @date    2017/2/28 11:49
 * @version 1.0
 */

import {Router} from "express";
import UserService from "../../service/user-service";
import WxMenuService from "../../service/weixin-menu-service";

const router = Router();

/**
 * 获取自定义菜单配置（API）
 */
router.get('/', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const access_token = await UserService.getAccessToken(userID);
            const result = await WxMenuService.getInfo(access_token);
            console.log(result.errcode);
            if (result.errcode === 46003) { // 菜单不存在
                return res.status(200).json({
                    "menu": {
                        "button": []
                    }
                });
            }
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取当前的菜单配置（API|网站）
 */
router.get('/current', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const access_token = await UserService.getAccessToken(userID);
            const result = await WxMenuService.getCurrentInfo(access_token);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 创建自定义菜单
 */
router.post('/create', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const menu = req.body.menu;
            const access_token = await UserService.getAccessToken(userID);
            const result = await WxMenuService.create({access_token, menu});
            // 更新使用列表
            const adNewsList = [];
            menu.button.forEach(item => {
                const isItem = !item.sub_button || item.sub_button.length === 0;
                const isNews = (item) => item.type === "click" && item.key.indexOf("news") >= 0;
                if (isItem) {
                    if (isNews(item)) adNewsList.push(item.key.split("__")[1]);
                } else {
                    item.sub_button.forEach(subItem => {
                        if (isNews(subItem)) adNewsList.push(subItem.key.split("__")[1]);
                    });
                }
            });
            let list = await UserService.updateAdNewsList({userID, list: adNewsList});
            console.log(list);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 删除自定义菜单
 */
router.post('/delete', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const access_token = await UserService.getAccessToken(userID);
            const result = await WxMenuService.remove(access_token);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

export default router;
